/**
 * @file {cf_pol目标库flaw表model}
 */
 'use strict'

 const { DataTypes, Model, Op } = require('../../../azeroth').sequelize;
 const {flawInitData} = require('../common/init_data');
 class FlawPol extends Model { }
 
 /**
  * @desc 映射需要的字段 【源库的 部分字段 --> 目标库字段】
  */
  const initFlawData = (sequelize_aim) => {
    FlawPol.init(
        ...flawInitData,
        {
            freezeTableName: true,
            sequelize: sequelize_aim,
            modelName: 'flaw',
            timestamps: false
        }
     )
  }
  FlawPol.getNewsPanelInfoFromLineDb = async (sequelize_aim, panelId) => {
    let sql = 'select * from flaw where panel_id = ' + panelId;
    let res = await sequelize_aim.query(sql, { type: sequelize_aim.QueryTypes.SELECT });
    return res[0];
  }

  FlawPol.getLatestFlawId = async (sequelize_aim) => {
    let sql = 'select max(uid) as uid from flaw';
    let res = await sequelize_aim.query(sql, { type: sequelize_aim.QueryTypes.SELECT });
    return res[0].uid;
  }
  /**
   * get flaw information by panel_id
   * @param {sequlize} sequelize_source
   * @param {String} panelId
   * @returns
   */
  FlawPol.getFlawInfoByPanelId = async (sequelize_source, queryStr) => {
    let query = typeof(queryStr) == 'string' ? `b.panel_id = "${queryStr}"` : `a.uid > ${queryStr} and a.uid <= (select max(uid) from flaw)`;

    let sql = 'select a.uid, a.job_id, b.panel_id, a.class_id, a.center_pos_md, a.center_pos_cd, a.length_md, a.length_cd, a.gen_time, a.gen_time_str, a.save_path, a.ui_show_text, a.camera_id ' + 
    'from flaw a inner join pol_aoi b on a.sheet_id = b.sheet_id where ' + query ;
    let res = await sequelize_source.query(sql, { type: sequelize_source.QueryTypes.SELECT });
    return res;
  }
  /**
   * 上传flaw信息
   * @param {Array} data 上传的缺陷信息数组
   * @returns
   */
  FlawPol.uploadPolInfo = async (data) => {
    // ignoreDuplicates: 忽略重复数据
    let res = await FlawPol.bulkCreate(data, {
      updateOnDuplicate : ['class_id', 'center_pos_md', 'center_pos_cd', 'length_md', 'length_cd', ' save_path', ' gen_time', ' gen_time_str', 'contours', 'ui_show_text', 'diameter', 'flaw_class_type', 'lot_id']
    });
    return res;
  }
 module.exports = {
     FlawPol,
     initFlawData
 };